package me.monster.smarttraffic.tool;

import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.StringRes;

import java.io.EOFException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okio.Buffer;

/**
 * @description
 * @author: Created jiangjiwei in 2018/11/1 12:49
 */
public class StringUtil {

    private static final Pattern PHONE_PATTERN = Pattern.compile("^[1][3456789]\\d{9}$");
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2," +
            "4})$");
    private static final Pattern MEDICAL_PATTERN = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,25}$");
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,16}$");

    public static boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            // Truncated UTF-8 sequence.
            return false;
        }
    }

    /**
     * 判断一个字符串是否为空值，包括，null null 字符串以及是否为全空格
     *
     * @param s 待判断的字符串
     * @return true 为空字符串，false 非空字符串
     */
    public static boolean isEmpty(CharSequence s) {
        if (TextUtils.isEmpty(s)) {
            return true;
        }
        if ("null".contentEquals(s)) {
            return true;
        }
        int len = s.length();
        for (int i = 0; i < len; i++) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断一个 Object 是否为空
     *
     * @param s 待判断的字符串
     * @return true 为空字符串，false 非空字符串
     */
    public static boolean isEmpty(Object s) {
        return s == null;
    }

    public static boolean isPhone(String string) {
        Matcher matcher = PHONE_PATTERN.matcher(string);
        return matcher.matches();
    }

    public static boolean isMedicalId(String id) {
        Matcher matcher = MEDICAL_PATTERN.matcher(id);
        return matcher.matches();
    }

    public static boolean isNotMedicalId(String id) {
        return !isMedicalId(id);
    }

    public static boolean isNotPhone(String string) {
        return !isPhone(string);
    }

    public static boolean isEmail(String email) {
        if (isEmpty(email)) {
            return false;
        }
        Matcher matcher = EMAIL_PATTERN.matcher(email);
        return matcher.matches();
    }

    public static boolean isNotEmail(String email) {
        return !isEmail(email);
    }

    public static boolean isPassword(@NonNull String password) {
        Matcher matcher = PASSWORD_PATTERN.matcher(password);
        return matcher.matches();
    }

    public static boolean isNotPassword(@NonNull String password) {
        return !isPassword(password);
    }

    /**
     * 判断字符串不为空
     *
     * @param s 字符串
     * @return
     */
    public static boolean isNotEmpty(CharSequence s) {
        return !isEmpty(s);
    }

    /**
     * 将一个 Object 数据组装为 String，如果 item == null or item == “null” 则空格
     *
     * @param objects 对象数组
     * @return
     */
    public static String append(Object... objects) {
        StringBuilder sb = new StringBuilder();
        for (Object object : objects) {
            if (null == object || "null".equals(object)) {
                sb.append(" ");
            } else {
                sb.append(object);
            }
        }
        return sb.toString();
    }

    public static String toString(Object o) {
        if (o == null) {
            return "";
        } else {
            return String.valueOf(o);
        }
    }

    public static String getString(@StringRes int id) {
        return Util.getApp().getString(id);
    }

    public static String getString(@StringRes int id, Object... formatArgs) {
        return Util.getApp().getString(id, formatArgs);
    }

    /**
     * 将一个 Object 类型转换为 字符串
     *
     * @param name Object
     * @return boolean
     */
    public static boolean parseBoolean(Object name) {
        String value = String.valueOf(name);
        return parseBoolean(value);
    }

    /**
     * 将字符串转换为 Boolean
     *
     * @param value string
     * @return Boolean
     */
    public static boolean parseBoolean(String value) {
        boolean flag = false;
        if (!isEmpty(value)) {
            if (value.endsWith(".0") || value.endsWith(".00")) {
                value = value.substring(0, value.indexOf("."));
                if ("1".equals(value)) {
                    value = "true";
                }
            } else if ("true".equals(value) || "True".equals(value)) {
                value = "true";
            }
        }
        flag = Boolean.parseBoolean(value);
        return flag;
    }

    private static boolean isNumeric(String s) {
        return s != null && s.matches("[-+]?\\d*\\.?\\d+");
    }

    public static int getInt(Object o) {
        String s = String.valueOf(o);
        if (isEmpty(s)) {
            return 0;
        }
        if (!isNumeric(s)) {
            return 0;
        }
        return Integer.parseInt(s);
    }

    public static String md5(String source) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(source.getBytes());
            StringBuilder buf = new StringBuilder();
            byte[] bits = md.digest();
            for (byte bit : bits) {
                int a = bit;
                if (a < 0) {
                    a += 256;
                }
                if (a < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(a));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return source;
        }
    }
}
